/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="openatc-serviceroute" style="position: relative">
    <!-- <div v-if="showService" @click="backClick" ref="titleBack" class="funcs">
      <i class="iconfont icon-fanhui"></i>
      <el-button type="text" class="title">
        {{ $t('openatc.main.back') }}</el-button
      >
    </div> -->
    <div class="onePageTable" ref="tableList">
      <div v-if="!showService" class="commonTablePanel openatc-grouplist">
        <div
          class="common-table-header"
          style="display: inline-block; width: 100%"
        >
          <div
            class="filter-container"
            style="float: right; margin-right: 20px"
          >
          <div class="filters" style="margin-left: 10px">
            <el-button
              class="add"
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
            >
              {{ $t('openatc.common.add') }}
            </el-button>
          </div>
            <div class="filters">
              <el-input
                @keyup.enter.native="getdevs()"
                v-model="devsfilter"
                :placeholder="$t('openatc.common.searchplaceholder')"
                style="width: 260px"
              >
                <el-button
                  slot="append"
                  @click="getdevs"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </div>
          </div>
        </div>
        <div class="atc-table" id="footerBtn">
          <el-table
            :data="tableData"
            size="mini"
            @row-click="onTableRow"
            :row-class-name="tableRowClassName"
            :max-height="tableHeight"
            style="width: 100%; font-size: 14px"
            v-loading.body="listLoading"
          >
            <el-table-column type="index" align="center"> </el-table-column>
            <!-- <el-table-column
              prop="id"
              min-width="10%"
              :label="$t('openatc.groupcontrol.id')"
              align="center"
            >
            </el-table-column> -->
            <el-table-column
              prop="name"
              :show-overflow-tooltip="true"
              min-width="20%"
              :label="$t('openatc.groupcontrol.name')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="devs"
              min-width="10%"
              :formatter="formatterNum"
              :label="$t('openatc.groupcontrol.roadnum')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="startname"
              :show-overflow-tooltip="true"
              min-width="20%"
              :label="$t('openatc.groupcontrol.start')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="endname"
              :show-overflow-tooltip="true"
              min-width="20%"
              :label="$t('openatc.groupcontrol.end')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="updatetime"
              min-width="20%"
              :label="$t('openatc.groupcontrol.updatetime')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="createtime"
              min-width="20%"
              :label="$t('openatc.groupcontrol.createtime')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="schedule"
              min-width="10%"
              :label="$t('openatc.groupcontrol.operateType')"
              :formatter="fomatState"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="state"
              min-width="10%"
              :label="$t('openatc.devicemanager.state')"
              align="center"
            >
              <template slot-scope="scope" v-if="scope.row.state !== 0">
                <el-tag size="medium" effect="plain" :type="getExecTag(scope.row).type">
                  {{ getExecTag(scope.row).label }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('openatc.groupcontrol.operation')"
              min-width="20%"
              align="center"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="handleToDetail(scope.row)">{{
                  $t('openatc.groupcontrol.control')
                }}</el-button>
                <el-button type="text" @click="handleEdit(scope.row)">{{
                  $t('openatc.groupcontrol.plan')
                }}</el-button>
                <el-button type="text" @click="doDelete(scope.row)">{{
                  $t('openatc.groupcontrol.delete')
                }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listQuery.pageNum"
            :page-size="listQuery.pageRow"
            :total="totalCount"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin: 0px"
          >
          </el-pagination>
        </div>
      </div>
      <Service
        :chooseId="chooseId"
        :editRoute="editRoute"
        @research="research"
        @backClick="backClick"
        v-if="showService"
      ></Service>
      <Messagebox
        :visible="deleteDiologVisible"
        :text="`${$t('openatc.greenwaveoptimize.isdelete')}${chooseName} ?`"
        @cancle="closeDeleteDialog"
        @ok="handleDelete"
      />
    </div>
    <div v-if="showRight">
      <dutyRoute
        :key="changeDuty"
        ref="dutyRoute"
        :params="params"
        @onStateSearch="onStateSearch"
        @onCloseClick="onCloseClick"
      />
    </div>
  </div>
</template>

<script>
import { getAllGroupList } from '../../api/table'
import { DeleteViproute } from '../../api/service'
import Service from './index.vue'
import dutyRoute from '../GisManager/components/dutyRoute/dutyRoute'
// import { SystemconfigApi } from '../../api/systemconfig.js'
import { getMessageByCode } from '../../utils/responseMessage'
import SelectAgentid from '../../components/SelectAgentid'
import SelectInfoType from '../../components/SelectInfoType'
import SelectReponseStatus from '../../components/SelectReponseStatus'
import Messagebox from '../../components/MessageBox'
import SelectControl from '../../views/Service/components/SelectControl'
import moment from 'moment'
import { getLanguage } from '../../utils/auth'
// import { getErrorMesZh, getErrorMesEn } from '../../utils/errorcode'
// import { getTheme } from '../../utils/auth.js'
export default {
  name: 'user',
  components: { Messagebox, dutyRoute, SelectAgentid, Service, SelectInfoType, SelectReponseStatus, SelectControl },
  data () {
    return {
      devsfilter: '',
      chooseName: '',
      chooseId: 0,
      params: {},
      showList: {},
      changeDuty: false,
      // isChange: false,
      editRoute: {},
      highLightRows: [],
      listState: null,
      isClickControl: false,
      showRight: false,
      contentStyle: {
        // height: window.innerHeight - 100 + 'PX'
        height: '100%'
      },
      deleteDiologVisible: false,
      showService: false,
      // menuOperateRecord: '',
      tableHeight: 700,
      screenHeight: window.innerHeight, // 屏幕高度
      listLoading: false,
      tableData: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 50 // 每页条数
      },
      totalCount: 0 // 分页组件--数据总条数
    }
  },
  watch: {
    screenHeight: function () {
      // 监听屏幕高度变化
      if (document.querySelector('#footerBtn')) {
        this.tableHeight =
          window.innerHeight -
          document.querySelector('#footerBtn').offsetTop -
          90
      }
    }
  },
  mounted: function () {
    // this.getMemu()
    this.listState = setInterval(() => {
      this.getList()
    }, 60000)
    this.getList()
    var _this = this
    _this.$nextTick(function () {
      // window.innerHeight:浏览器的可用高度
      // this.$refs.table.$el.offsetTop：表格距离浏览器的高度
      // 后面的50：根据需求空出的高度，自行调整
      if (document.querySelector('#footerBtn')) {
        _this.tableHeight =
          window.innerHeight -
          document.querySelector('#footerBtn').offsetTop -
          90
      }
      window.onresize = function () {
        // 定义窗口大小变更通知事件
        _this.screenHeight = window.innerHeight // 窗口高度
      }
      let language = getLanguage()
      if (language === 'zh') {
        document.getElementsByClassName('el-pagination__jump')[0].childNodes[0].nodeValue = '前往第'
      } else {
        document.getElementsByClassName('el-pagination__jump')[0].childNodes[0].nodeValue = 'Go To'
      }
    })
  },
  methods: {
    fomatState (row) {
      let res = ''
      if (row.schedule === 0) {
        res = this.$t('openatc.groupcontrol.manual')
      } else if (row.schedule === 1) {
        res = this.$t('openatc.groupcontrol.auto')
      }
      return res
    },
    getExecTag (row) {
      let res = {
        label: this.$t('openatc.dutyroute.onduty'),
        type: 'success'
      }
      if (row.state === 0) {
        res = {
          label: this.$t('openatc.dutyroute.notonduty'),
          type: 'info'
        }
      } else if (row.state === 1) {
        res = {
          label: this.$t('openatc.dutyroute.onduty'),
          type: 'success'
        }
      } else if (row.state === 2) {
        res = {
          label: this.$t('openatc.dutyroute.onwait'),
          type: 'info'
        }
      }
      return res
    },
    onSearchClick () {
      this.getList()
    },
    onTableRow (row) {
      this.highLightRows = []
      const exists = this.highLightRows.includes(row)
      if (exists) {
        this.highLightRows = this.highLightRows.filter(item => item !== row)
      } else {
        this.highLightRows.push(row)
      }
    },
    tableRowClassName ({ row }) {
      for (let i = 0; i < this.highLightRows.length; i++) {
        // 重置高亮行
        if (this.highLightRows[i] === row) {
          return 'highLight-row'
        }
      }
    },
    onStateSearch (route) {
      let record = this.tableData.find(item => item.id === route.id)
      let dev = route.devs.find(item => item.state === 1)
      if (dev) {
        route.state = dev ? 1 : 0
      }
      if (record && record.state !== route.state) {
        record.state = route.state
      }
    },
    onCloseClick () {
      this.showRight = false
      this.isClickControl = false
      this.$refs.tableList.style.width = '100%'
    },
    doDelete (row) {
      this.chooseName = row.name
      this.chooseId = row.id
      this.deleteDiologVisible = true
    },
    research (route) {
      this.changeDuty = !this.changeDuty
      // this.showRight = true
      this.showService = false
      this.$nextTick(() => {
        this.params = {
          type: '1',
          row: route === undefined ? this.showList : route
        }
      })
      if (this.isClickControl) {
        this.showRight = true
        this.$nextTick(() => {
          this.$refs.tableList.style.width = (window.innerWidth - 360) + 'PX'
        })
      }
      this.getList()
    },
    handleDelete () {
      // const route = this.planData.find(item => item.id === this.chooseId)
      DeleteViproute(this.chooseId).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.getList()
        this.showRight = false
        this.$refs.tableList.style.width = '100%'
        this.deleteDiologVisible = false
        this.$message({
          message: this.$t('openatc.common.deletesuccess'),
          type: 'success',
          duration: 1 * 1000,
          onClose: () => {
            // this.chooseId = 0
            // this.$emit('research', route)
          }
        })
      })
    },
    closeDeleteDialog () {
      this.deleteDiologVisible = false
    },
    getReqData () {
      let reqData = {}
      let from = moment(this.timeValue[0]).format('YYYY-MM-DD HH:mm:ss')
      let to = moment(this.timeValue[1]).format('YYYY-MM-DD HH:mm:ss')
      let agentid = this.$refs.selectAgentid.value
      let infotype = this.$refs.selectInfoType.value
      let status = this.$refs.selectReponseStatus.value
      reqData = {
        source: this.source,
        infotype: infotype,
        response_code: status,
        agentId: agentid,
        operator: this.operator,
        beginTime: from,
        endTime: to,
        pageNum: this.listQuery.pageNum,
        pageRow: this.listQuery.pageRow
      }
      return reqData
    },
    getdevs () {
      this.getList()
    },
    handleAdd () {
      this.showService = true
      this.editRoute = {}
      this.chooseId = 0
      this.showRight = false
      this.$nextTick(() => {
        this.$refs.tableList.style.width = '100%'
      })
    },
    formatterNum (row, column) {
      return row.devs.length
    },
    getList () {
      this.listLoading = true
      let startTime = new Date().getTime()
      getAllGroupList(this.devsfilter ? this.devsfilter : '*').then(data => {
        let endTime = new Date().getTime()
        let diffTime = endTime - startTime
        if (diffTime < 100) {
          setTimeout(() => {
            this.listLoading = false
          }, 1000 * 0.2)
        } else {
          this.listLoading = false
        }
        if (data.data.success !== true) {
          this.listLoading = false
          if (data.data.code === '20004') {
            this.$message.error('无参数记录!')
            return
          }
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.tableData = this.handleData(data.data.data)
        this.totalCount = data.data.data.length
      })
    },
    handleToDetail (row) {
      this.isClickControl = true
      this.showList = row
      this.changeDuty = !this.changeDuty
      this.showRight = true
      this.$nextTick(() => {
        this.params = {
          type: '1',
          row: row
        }
      })
      this.$refs.tableList.style.width = (window.innerWidth - 360) + 'PX'
    },
    handleEdit (row) {
      this.onTableRow(row)
      this.showService = true
      this.chooseId = row.id
      this.editRoute = row
      this.showRight = false
      this.showList = row
      this.$nextTick(() => {
        this.params = {
          type: '1',
          row: row
        }
      })
      if (this.isClickControl) {
        this.$nextTick(() => {
          this.$refs.tableList.style.width = '100%'
        })
      }
    },
    backClick () {
      this.backClicks()
    },
    backClicks () {
      this.showService = false
      if (this.isClickControl) {
        this.showRight = true
      }
      this.$nextTick(() => {
        this.params = {
          type: '2',
          row: this.showList
        }
        if (this.isClickControl) {
          this.$refs.tableList.style.width = (window.innerWidth - 360) + 'PX'
        }
      })
    },
    handleData (data) {
      data.forEach(item => {
        if (item.devs.length === 0) return
        item.startname = item.devs[0].name
        item.endname = item.devs[item.devs.length - 1].name
      })
      return data
    },
    handleSizeChange (val) {
      // 改变每页数量
      this.listQuery.pageRow = val
      this.getList()
    },
    handleCurrentChange (val) {
      // 改变页码
      this.listQuery.pageNum = val
      this.getList()
    }
  },
  destroyed () {
    clearInterval(this.listState)
    this.listState = null
  }
}
</script>

<style lang="scss" scoped>
/deep/.add {
  padding-left: 14PX;
  padding-right: 14PX;
}
/deep/.gis-duteRoute .block {
}
</style>
